package com.kaikeba.web;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
 * 功能：处理文件下载请求
 */
@WebServlet("/downloadImg")
public class DownLoadImg extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1、获取文件名
        String filename = req.getParameter("filename");
        //2、指定需要下载的文件的路径
        String path = "/uploadFiles/"+filename;
        //3、设置响应的头部信息和响应类型
        resp.setContentType("application/octet-stream");
        //告诉浏览器有一个文件需要下载，为了避免中文文件名导致乱码，可以对文件名指定编码，URLEncoding.Encode(filename,"UTF-8");
        resp.addHeader("Content-Disposition","attachment;filename="+ filename);
        //4、跳转页面
        req.getRequestDispatcher(path).forward(req,resp);
        //5、清空缓冲区
        resp.flushBuffer();
    }
}
